<?php

require_once "db_config.php";

class DBConn {
	
	private $conn;
	
	public function __construct() { 
		set_time_limit(20);
		
		$conn = mysqli_connect(TravelHard\DB_HOST, TravelHard\DB_USERNAME, TravelHard\DB_PASSWORD, TravelHard\DB_NAME);
		if (mysqli_connect_errno()) { 
			printf("Connect failed: %s\n", mysqli_connect_error()); 
			exit(); 
		}
		$this->conn = $conn;
	}
	
	public function __destruct() {
		if ($this->conn !== NULL) {
			mysqli_close($this->conn);
		}
	}
	
	public function query($query) {
		$this->check_connection();
		$result = mysqli_query($this->conn, $query);
		return $result;
	}
	
	public function sanitize($input) {
		if (is_string($input)) {
			return "'" . mysqli_real_escape_string($this->conn, $input) . "'";
		}
		return $input;
	}
	
	public function prepare_for_transaction(){
		$result = mysqli_autocommit($this->conn, FALSE);
		if (!$result) {
			error_exit("autocommit");
		}
		return $result;
	}

	public function commit_transaction(){
		$result = mysqli_commit($this->conn);
		if (!$result) {
			error_exit("commit");
		}
		return $result;
	}

	/******* PRIVATE HELPER FUNCTIONS *******/
	private function check_connection() {
		if(!$this->conn) { 
			printf("No connection currently exists.\n");
			exit(); 
		}
	}

	private function error_exit ($errormsg="unspecified"){
		echo "<p>We're sorry: a system error occurred.</p>";
		echo "Error Message: " . $errormsg;
		mysqli_rollback($this->conn);
		mysqli_close($this->conn);
		exit();
	}
}

?>
